﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.SS.Util;
using HorizontalAlignment = NPOI.SS.UserModel.HorizontalAlignment;

namespace Wlx.MobileStats.GIONEE
{
    public partial class StatsForm : Form
    {
        private readonly List<ImportFileModel> _importFiles = new List<ImportFileModel>();
        private BindingList<StatsModel> _bindingList = new BindingList<StatsModel>();

        private const string SnNumberPattern = "SN Number =(\\w*)\\s";
        private const string TestDateTimePattern = "^Date: ([0-9|-]*)\\s*Time: ([0-9|:]*)\\s*$";
        private const string TestResultPattern = "cal\\s*(check\\s*)?(\\bok|fail\\b),value(\\(\\s*[0-9|.|-]*\\s*\\<\\s*)?([0-9}.|-]*)(\\s*\\<\\s*[0-9|.|-]*\\))?\\s*$";

        public StatsForm()
        {
            InitializeComponent();
            InitGrid();
        }

        private void InitGrid()
        {
            _bindingList = new BindingList<StatsModel>();
            DataGrid.DataSource = _bindingList;
            DataGrid.ScrollBars = ScrollBars.Vertical;
            DataGrid.ReadOnly = true;
            DataGrid.Columns[0].HeaderText = @"Date";
            DataGrid.Columns[0].Width = 85;
            DataGrid.Columns[1].HeaderText = @"Time";
            DataGrid.Columns[1].Width = 85;
            DataGrid.Columns[2].HeaderText = @"SN Number";
            DataGrid.Columns[2].Width = 141;
            DataGrid.Columns[3].HeaderText = @"Result";
            DataGrid.Columns[3].Width = 80;
            DataGrid.Columns[4].HeaderText = @"Value";
            DataGrid.Columns[4].Width = 88;
        }

        private void ImportBtn_Click(object sender, EventArgs e)
        {
            var fileDialog = new OpenFileDialog
            {
                Multiselect = true,
                Title = @"请选择文件",
                Filter = @"所有文件(*.*)|*.*"
            };
            if (fileDialog.ShowDialog() == DialogResult.OK)
            {
                var count = fileDialog.FileNames.Length;
                if (fileDialog.CheckFileExists)
                {
                    ClearListBox();
                    for (var i = 0; i < count; i++)
                    {
                        var name = fileDialog.SafeFileNames[i];
                        var path = fileDialog.FileNames[i];
                        _importFiles.Add(new ImportFileModel(name, path));
                        FileListBox.Items.Add(name);
                    }
                }
                ScanFiles();
            }
        }

        private void ClearListBtn_Click(object sender, EventArgs e)
        {
            ClearListBox();
        }

        private void ExportBtn_Click(object sender, EventArgs e)
        {
            var exportDialog = new SaveFileDialog  //导出文件的弹窗设置
            {
                FileName = "Test Result " + DateTime.Now.ToString("yyyyMMddHHmmss"),
                Filter = @"导出Excel(*.xls)|*.xls"
            };
            if (exportDialog.ShowDialog() == DialogResult.OK)  //确认是否导出
            {
                var filePath = exportDialog.FileName;   //导出的文件路径
                if (File.Exists(filePath))             //判断导出的excel是否已存在，如果存在，会提示文件名存在，无法导出。
                {
                    MessageBox.Show(@"该文件名已存在，请重新导出");
                    return;
                }
                using (var fs = new FileStream(filePath, FileMode.CreateNew, FileAccess.ReadWrite))  //将数据写入文件流中，并生成文件
                {
                    var excel = new HSSFWorkbook();  //初始化一个excel对象
                    ISheet sheet = excel.CreateSheet("Test Result");  //excel新建一个表单
                    FillDataInSheet(sheet);   //将数据信息写入表单中

                    excel.Write(fs);
                    fs.Position = 0;
                    fs.Flush();
                }
                MessageBox.Show(@"提示： 创建成功！");
            }
        }

        private void ClearListBox()
        {
            _importFiles.Clear();
            _bindingList.Clear();
            FileListBox.Items.Clear();
            LoadLabel.Text = @"已导入0个文件";
            BuildLabel.Text = @"已加载0条有效数据";
        }

        private void ScanFiles()
        {
            foreach (var fileModel in _importFiles)
            {
                BuildFileModel(fileModel);
                if (fileModel.IsRegular)
                {
                    _bindingList.Add(fileModel.Stats);
                }
            }
            LoadLabel.Text = @"已导入" + _importFiles.Count + @"个文件";
            BuildLabel.Text = @"已加载" + _bindingList.Count + @"条有效数据";
        }

        private void BuildFileModel(ImportFileModel fileModel)
        {
            var lines = File.ReadAllLines(fileModel.Path);
            foreach (var line in lines)
            {
                var snNumMatches = Regex.Matches(line, SnNumberPattern);
                if (snNumMatches.Count > 0)
                {
                    var snMatch = snNumMatches[0];
                    fileModel.Stats.SnNumber = snMatch.Groups[1].Value;
                    fileModel.IsRegular = true;
                    continue;
                }
                var dateTimeMatches = Regex.Matches(line, TestDateTimePattern);
                if (dateTimeMatches.Count > 0)
                {
                    var dtMatch = dateTimeMatches[0];
                    fileModel.Stats.TestDate = dtMatch.Groups[1].Value;
                    fileModel.Stats.TestTime = dtMatch.Groups[2].Value;
                    continue;
                }
                var valueMatches = Regex.Matches(line, TestResultPattern);
                if (valueMatches.Count > 0)
                {
                    var valMatch = valueMatches[0];
                    fileModel.Stats.TestResult = valMatch.Groups[2].Value;
                    fileModel.Stats.TestValue = valMatch.Groups[4].Value;
                }
            }
        }

        private void FillDataInSheet(ISheet sheet)
        {
            #region fill title
            var titleRow = sheet.CreateRow(0);
            sheet.SetColumnWidth(0, 3000);
            sheet.SetAutoFilter(CellRangeAddress.ValueOf("A1:F1"));
            sheet.SetColumnWidth(1, 4000);
            sheet.SetColumnWidth(2, 4000);
            sheet.SetColumnWidth(3, 8000);
            sheet.SetColumnWidth(4, 4000);
            sheet.SetColumnWidth(5, 4000);
            sheet.CreateFreezePane(0, 1, 0, 1);
            for (var i = 0; i < 6; i++)
            {
                titleRow.CreateCell(i);
            }
            titleRow.Cells[0].SetCellValue("NO.");
            titleRow.Cells[0].CellStyle.Alignment = HorizontalAlignment.Center;

            titleRow.Cells[1].SetCellValue("Test Date");
            titleRow.Cells[1].CellStyle.Alignment = HorizontalAlignment.Center;

            titleRow.Cells[2].SetCellValue("Test Time");
            titleRow.Cells[2].CellStyle.Alignment = HorizontalAlignment.Center;

            titleRow.Cells[3].SetCellValue("SN NO.");
            titleRow.Cells[3].CellStyle.Alignment = HorizontalAlignment.Center;

            titleRow.Cells[4].SetCellValue("Test Result");
            titleRow.Cells[4].CellStyle.Alignment = HorizontalAlignment.Center;

            titleRow.Cells[5].SetCellValue("Test Value");
            titleRow.Cells[5].CellStyle.Alignment = HorizontalAlignment.Center;
            #endregion

            #region fill data

            var index = 1;
            foreach (var stats in _bindingList)
            {
                var row = sheet.CreateRow(index);
                for (var i = 0; i < 6; i++)
                {
                    row.CreateCell(i);
                }
                row.Cells[0].SetCellValue(index);
                row.Cells[0].CellStyle.Alignment = HorizontalAlignment.Center;
                row.Cells[1].SetCellValue(stats.TestDate);
                row.Cells[1].CellStyle.Alignment = HorizontalAlignment.Center;
                row.Cells[2].SetCellValue(stats.TestTime);
                row.Cells[2].CellStyle.Alignment = HorizontalAlignment.Center;
                row.Cells[3].SetCellValue(stats.SnNumber);
                row.Cells[3].CellStyle.Alignment = HorizontalAlignment.Center;
                row.Cells[4].SetCellValue(stats.TestResult);
                row.Cells[4].CellStyle.Alignment = HorizontalAlignment.Center;
                row.Cells[5].SetCellValue(stats.TestValue);
                row.Cells[5].CellStyle.Alignment = HorizontalAlignment.Center;
                index++;
            }

            #endregion
        }
    }
}
